<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-scrollbar class="w-full h-full">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="分类能耗：">
                <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="small" @change="changeMeter()">
                  <el-option
                    v-for="(item, index) in meterTypeList" :key="index"
                    :label="item.paramValue"
                    :value="item.paramKey">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item class="el-form-item--mini" label="日期: ">
                <el-select v-model="dataForm.dateType" placeholder="请选择"  size="small" style="width: 80px;">
                  <el-option
                    v-for="(item, index) in Config.searchDate" :key="index"
                    :label="item.label"
                    :value="item.date">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item  label-width="40px" class="el-form-item--mini">
                <el-date-picker
                  v-model="dataForm.date"
                  placeholder="时间"
                  style="width: 200px;"
                  class="filter-item"
                  size="small"
                  :type="dataForm.dateType"
                  suffix-icon="el-icon-date"
                  clearable
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item  label-width="40px" class="el-form-item--mini">
                <el-button type="primary" size="small" icon="el-icon-search"  @click="getPowerDataList" style="margin-left:16px;">查询</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="flex mt-4">
          <div class="p-4 flex-2 mr-4" style="background-color:rgba(0,0,0,.1);">
            <div class="flex-1" id="itemOverview_analysis_bar" style="height:300px;"></div>
          </div>
          <div class="p-4 flex-1" style="background-color:rgba(0,0,0,.1);">
            <div class="flex-1" id="itemOverview_analysis_pie" style="height:300px;"></div>
          </div>
        </div>
        <div class="mt-4">
          <div class="flex mb-4" v-for="(i, index) in list" :key="index">
            <div style="width:15%;background-color:rgba(0,0,0,.1);" class="flex flex-col items-center justify-center py-2 mr-4">
              <img class="w-12 h-12" :src="importImage(i.name)"  />
              <span class="theme-front-color text-sm mt-2">{{i.title}}</span>
            </div>
            <div class="flex-1 flex">
              <table class="flex-1 mr-4 border-collapse" v-for="(j, inx) in i.data" :key="'table-' + inx">
                <tr v-for="(k, ind) in j" :key="'tr-' + ind">
                  <td class="border" :style="{'border-color': activeSetting.name === 'd2' ? '#999' : '#999'}">
                    <div class="flex item-center px-2 py-1 text-sm theme-front-color">
                      <span class="flex-1">{{k.label}}</span>
                      <span class="font-bold" :class="k.label=='趋势'&&k.value.indexOf('-')== -1 ? 'changeRed':(k.label=='趋势'&&k.value.indexOf('-')!= -1?'changeGreen':'')">{{k.value}} {{ k.label!='趋势'?currentUnit:'' }}</span>
                      <i v-if="k.label=='趋势'&&k.value!='--'&&k.value.indexOf('-')== -1" style="color: #E31B1B" class="el-icon-top"></i>
                      <i v-if="k.label=='趋势'&&k.value!='--'&&k.value.indexOf('-')!= -1" style="color: #9ddf1e" class=" el-icon-bottom"></i>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </d2-container>
</template>

<script>
  import { mapGetters } from 'vuex'
  import areaTree from './compont/area_tree_onceclick'
  import * as echarts from 'echarts'
  import dayjs from 'dayjs'
  import Config from "@/utils/config";
  import * as Util from "@/utils";
  export default {
    name: 'itemOverview',
    data() {
      return {
        currentUnit:'',
        dataForm:{
          energyType: '',
          date:new Date(),
          dateType: 'date',
          subEnergyType:[],//分项选择值
        },
        subItemList:[],
        meterTypeList:[],
        Config:Config,
        buildList:[],
        list: [
          // {
          //   name: 'zmyd',
          //   title: '照明用电',
          //   data: [
          //     [
          //       {
          //         label: '当日',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '昨日同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当月',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '上月同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当年',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '去年同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ]
          //   ]
          // },
          // {
          //   name: 'ktyd',
          //   title: '空调用电',
          //   data: [
          //     [
          //       {
          //         label: '当日',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '昨日同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当月',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '上月同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当年',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '去年同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ]
          //   ]
          // },
          // {
          //   name: 'czyd',
          //   title: '插座用电',
          //   data: [
          //     [
          //       {
          //         label: '当日',
          //         value: '149.63 kW·h',
          //       },
          //       {
          //         label: '昨日同期',
          //         value: '173.2 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '-13.61%',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当月',
          //         value: '1427.01 kW·h',
          //       },
          //       {
          //         label: '上月同期',
          //         value: '1289.99 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '10.62%',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当年',
          //         value: '5632.8 kW·h',
          //       },
          //       {
          //         label: '去年同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ]
          //   ]
          // },
          // {
          //   name: 'tsyd',
          //   title: '特殊用电',
          //   data: [
          //     [
          //       {
          //         label: '当日',
          //         value: '2.39 kW·h',
          //       },
          //       {
          //         label: '昨日同期',
          //         value: '3.13 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '-23.64%',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当月',
          //         value: '23.58 kW·h',
          //       },
          //       {
          //         label: '上月同期',
          //         value: '30.43 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '-22.51%',
          //       }
          //     ],
          //     [
          //       {
          //         label: '当年',
          //         value: '113.83 kW·h',
          //       },
          //       {
          //         label: '去年同期',
          //         value: '0 kW·h',
          //       },
          //       {
          //         label: '趋势',
          //         value: '--',
          //       }
          //     ]
          //   ]
          // }
        ]
      }
    },
    computed: {
      ...mapGetters('d2admin/theme', ['activeSetting'])
    },
    components: {
      areaTree
    },
    watch: {
      'activeSetting.name': {
        handler() {
          this.getPowerDataList()
        },
        immediate: true,
      },
      'dataForm.energyType':function(newV,oldV){
        this.currentUnit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
      },
    },
    created() {
      this.$nextTick(()=>{
        this.queryStatic("METER_TYPE",null,data=>{
          if (data && data.code === 0) {
            this.meterTypeList = data.page
            this.dataForm.energyType = data.page[0].paramKey;
            this.currentUnit = data.page[0].paramExt;
            this.changeMeter()
          } else {
            this.meterTypeList = []
          }
          // this.getPowerDataList();
        });
      })

    },
    methods: {
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{paramValue,paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      importImage(name) {
        if(name == ''){
          name = 'tsyd'
        }
        return require(`@/assets/itemOverview/${name}-${this.activeSetting.name}.png`)
      },
      treeNodeChange(data){
        this.buildList = data
        if(this.dataForm.energyType.length == 0 || this.dataForm.subEnergyType.length == 0){
          setTimeout(() => {
            this.treeNodeChange(data);
          }, 500)
        }else {
          this.getPowerDataList()
        }
      },
      formarDate(type, date) {
        return Util.dateFormat(Config.searchDate.find(item => item.date == type).format, date)
      },

      changeMeter(){
        this.queryStatic("SUBITEM_VAL",this.dataForm.energyType,data1=> {
          if (data1 && data1.code === 0) {
            this.subItemList = data1.page
            this.dataForm.subEnergyType = this.subItemList.map(i => i.paramKey);
          } else {
            this.subItemList = []
          }
        });
      },
      objArraySort(objArr, key)
      {
        let result = objArr.slice(0);
        return result.sort((a, b) => parseInt(a[key]) - parseInt(b[key]));
      },
      /**
       * 查询数据
       * */
      getPowerDataList() {
        if(this.dataForm.energyType.length == 0 || this.dataForm.subEnergyType.length == 0){
          return
        }
        const chart = echarts.init(document.querySelector('#itemOverview_analysis_bar'))
        chart.clear()
        const chartPie = echarts.init(document.querySelector('#itemOverview_analysis_pie'))
        chartPie.clear()
        this.meterdataList = []
        this.$api.okhttp({
          url:this.$http.adornUrl('/eas/dmyReport/subitemlist'),
          method: "post",
          data: this.$http.adornParams(
            {
              buildingIds: [this.buildList],
              date: (this.dataForm.date&&this.dataForm.date!="")? this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):'',
              dateType: Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,
              meterType: this.dataForm.energyType,
              subEnergyTypes: this.dataForm.subEnergyType,
              customerId: this.$util.cookies.get("customer_id"),
              projectId:this.$util.cookies.get("cuuren_projectId")
            }
          )
        }).then((data) => {
          if (data && data.code === 0) {
            this.drawBar(data.data)
            this.drawPie(data.data);
          }
        })
        this.list = []
        this.$api.okhttp({
          url:this.$http.adornUrl('/eas/dmyReport/subitemTotallist'),
          method: "post",
          data: this.$http.adornParams(
            {
              buildingIds: [this.buildList],
              date: (this.dataForm.date&&this.dataForm.date!="")? this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):'',
              dateType: Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,
              meterType: this.dataForm.energyType,
              subEnergyTypes: this.dataForm.subEnergyType,
              customerId: this.$util.cookies.get("customer_id"),
              projectId:this.$util.cookies.get("cuuren_projectId")
            }
          )
        }).then((data) => {
          if (data && data.code === 0) {
             this.list = data.data
          }
        })

      },

      drawBar(data) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#itemOverview_analysis_bar'))
          let seriesArry = []
          let xdata = []
          for(let i = 0;i<data.length;i++){
            if(data[i].subitemName !== '合计'){
              let val = data[i].val;
              let valueArry = []
              Object.keys(val).forEach((key) => {
                valueArry.push({"id":key,"value":val[key]})
              })
              valueArry = this.objArraySort(valueArry, "id")
              // let xMax = 0;
              // if(this.dataForm.dateType == 'date'){
              //   xMax = new Date().getHours();
              //
              // }else if(this.dataForm.dateType == 'month'){
              //   xMax = new Date().getDate();
              //
              // } else if(this.dataForm.dateType == 'year'){
              //   xMax = new Date().getMonth()+1;
              // }
              // valueArry = valueArry.slice(0,xMax)
              xdata = valueArry.map(i=>i.id)
              let ydata = valueArry.map(i=>i.value)

              seriesArry.push({
                data: ydata,
                type: 'bar',
                name: data[i].subitemName,
                stack: 'use'
              })
            }
          }
          chart.setOption({
            grid: {
              left: '5%',
              right: '5%',
              top: '5%',
              bottom: '5%'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            grid: {
              left: '10%',
              right: '5%',
              top: '10%',
              bottom: '10%'
            },
            xAxis: {
              type: 'category',
              data: xdata,
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
            },
            yAxis: {
              name: this.currentUnit,
              nameTextStyle: {
                align: "right"
              },
              type: 'value',
              axisLine: {
                lineStyle: {
                  color: this.activeSetting.name === 'd2' ? '#333' : '#999'
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: ['#999']
                },
              },
            },
            legend: {
              right: 20,
              textStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#ccc'
              },
            },
            series: seriesArry
          })
        })
      },
      drawPie(data) {
        this.$nextTick(() => {
          const chart = echarts.init(document.querySelector('#itemOverview_analysis_pie'))
          let seriesArry = []
          for(let i = 0;i<data.length;i++) {
            if (data[i].subitemName !== '合计') {
              seriesArry.push({
                name: data[i].subitemName, value:data[i].totalVal
              })
            }
          }

          chart.setOption({
            grid: {
              left: '5%',
              right: '5%',
              top: '5%',
              bottom: '5%'
            },
            tooltip: {
              trigger: 'item',
              formatter: '{b}: {c}'+this.currentUnit+' ({d}%)'
            },
            // legend: {
            //   right: 20,
            //   textStyle: {
            //     color: this.activeSetting.name === 'd2' ? '#333' : '#ccc'
            //   },
            // },
            label: {
              show: true,
              overflow: 'breakAll',
              formatter(param) {
                return param.name + ' (' + param.percent  + '%)';
              }
            },
          	series: [
          		{
          			type: 'pie',
          			data: seriesArry,
                radius: ['40%', '60%'],
                emphasis: {
                  label: {
                    show: true,
                    fontSize: 16,
                    fontWeight: 'bold'
                  },
                  focus: 'self'
                },
                labelLine: {
                  show: true
                },
          		}
          	]
          })
        })
      },
    },
  }
</script>

<style>
  .changeRed{
    color: #E31B1B;
  }

  .changeGreen{
    color: #9ddf1e;
  }
</style>
